module LockDown
  SESSION_TIMEOUT = 1.hour
  
  PASSWORD_RESET_TIMEOUT = 24.hour
                  
  SECURITY_SALT = "012345678901234567890123"
  
  #
  # Define your roles for the system.  The first is the admin role and will
  # have access to the management screens included with this plugin.
  # You can add as many roles has you would like, but I recommend keeping
  # your number of roles to a minimum.  The user group functionality will
  # allow you to dynamically mix and match permissions without having to create
  # a bunch of static roles.
  #
  # The hash values MUST correspond to their database ids.
  #
  ROLES = {:admin => 1, :user => 2}
  
  
  class << self
    def role_name(id)
      LockDown::ROLES.index(id).to_s if LockDown::ROLES.has_value?(id)
    end
    #
    # URL formatting
    #
    def format_action(action)
      format_controller_action(controller_path, action)
    end

    def format_controller_action(ctroller, action)
      format_controller(ctroller) << "/" << action
    end
      
    def format_controller(ctroller)
      cname = ""
      parts = ctroller.split("/")
      parts.delete_if{|p| p.length == 0}.join("/")
    end
    
    def public_actions
      actions = []
      sg = SystemObject.find(1)
      sg.system_method.each{|sa| actions <<  sa.name }
      actions
    end

    def protected_actions(user_id)
      return [] if user_id.nil? 

      user = User.find(user_id)

      all_users = find_static_permissions 
      return all_users + load_by_user_group(user) unless user.user_group.length == 0

      return all_users + load_by_user_role(user)
    end

    private        
      #
      # Convention is to have your first system object be the public object.
      # therefore all system methods for this object are always accessible.
      #
      def find_static_permissions
        actions = []
        methods_from_system_object_id(1){|meth| actions <<  meth }
        actions
      end

      def methods_from_system_object_id(id)
        sysob = SystemObject.find(id)
        sysob.system_method.each{|sa| yield sa.name }
      rescue ActiveRecord::RecordNotFound
      end

      def load_by_user_role(user)
        actions = []
        user.role.system_object.each do |rso|
          rso.system_method.each{|sm| actions <<  sm.name unless actions.include?(sm.name)}
        end
        actions
      end

      def load_by_user_group(user)
        actions = []
        user.user_group.each do |ug|
          ug.system_object.each do |ugso|
            ugso.system_method.each{|sm| actions <<  sm.name unless actions.include?(sm.name)}
          end 
        end
        actions
      end
  end #end class block 
end
